package com.joe.xl.devcommon1.util.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @Author joexl <joe_xuli@163.com>
 * @Since 1.0
 * @Date 2020/10/24
 */
public class KafkaConsumerStart {
    private final static String KAFKA_SERVER_URL = "192.168.78.128:9092,192.168.78.128:9093,192.168.78.128:9094";
    private final static String KAFKA_GROUP_ID = "joe.demo1";

    public static void main(String... args){
        Properties props = new Properties();
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); //key序列化器
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); //值序列化器
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_SERVER_URL); // kafka服务器地址
        props.put(ConsumerConfig.GROUP_ID_CONFIG, KAFKA_GROUP_ID); //

        String topic = "testhello";
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(props);

        kafkaConsumer.subscribe(Collections.singletonList(topic));
        // kafkaConsumer.subscribe(Pattern.compile("joe*"));  //订阅正则的topic
        // kafkaConsumer.assign(Collections.singletonList(new TopicPartition(topic, 0))); //指定订阅具体的分区id

        while(true) {
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("--Received message KafkaConsumerInit: (topic->" +
                        record.topic() + ", partition->" + record.partition() + ", key->"
                        + record.key() + ", value->" + record.value() + "), at offset " + record.offset());
            }
        }

    }

}
